/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bsc.minacommand.json;

import com.bsc.minacommand.model.AbstractBscCommand;
import com.bsc.util.datas.StringUtil;
import com.bsc.util.json.ExtHelper;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import org.apache.commons.lang.StringUtils;
import org.apache.mina.core.buffer.IoBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 通过json，对象和字节之间的转换。
 *
 * @author penn.ma
 */
public class TransJson implements AbstractTransJson {

    private static final Logger LOGGER = LoggerFactory.getLogger(TransJson.class);

    /**
     *
     * @param clazz
     * @param bytes
     * @return T 使用json工具将字节转化成对象
     */
    public Object TransJsonByte(Class clazz, byte[] bytes) {

        if (bytes.length > 0) {
            try {
                Object newObject = clazz.newInstance();
                String ojson = StringUtils.trim(new String(bytes, "UTF-8"));
                newObject = ExtHelper.getBeanFormJson(ojson, clazz);
                return newObject;
            } catch (Exception ex) {
                LOGGER.error("transJsonByte command error!", ex);
            }
        }
        return null;
    }

    /**
     *
     * @param obj
     * @return 将对象封装成 T(默认byte数组)
     */
    public byte[] TransJsonObject(Object obj) {
        if (obj != null && obj instanceof AbstractBscCommand) {
            IoBuffer buffer = IoBuffer.allocate(128);
            buffer.setAutoExpand(true);
            try {
                String ojson = ExtHelper.getJsonFromBean(obj);
                buffer.put(ojson.getBytes("UTF-8"));
                return buffer.array();
            } catch (Exception e) {
                LOGGER.error("TransJsonObject command error !", e);
            }
        }
        return null;
    }
}
